package com.gzdh.tang.dishrecognition;

import org.apache.commons.codec.binary.Base64;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.security.*;
import java.security.cert.*;
import java.security.cert.Certificate;
import java.util.Enumeration;

/**
 * Description: 读取P12格式的个人交换库
 * <p>
 * User: lishaohua
 * Date: 2017/12/27  12:51
 */
public class P12Demo {

    public static void main(String[] args) throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {
        String keyStorePath = "D:\\apiclient_cert.p12";
        String password = "1451483202";

        BigDecimal amountPrice = new BigDecimal("25.42");
        System.out.println(String.format(amountPrice.toPlainString(), "￥%1$.2f", 21F));
        ;


        // 实例化密钥库，默认JKS类型
        KeyStore ks = KeyStore.getInstance("PKCS12");
        // 获得密钥库文件流
        FileInputStream is = new FileInputStream(keyStorePath);
        // 加载密钥库
        ks.load(is, password.toCharArray());
        // 关闭密钥库文件流
        is.close();

        //私钥
        Enumeration aliases = ks.aliases();
        String keyAlias = null;
        if (aliases.hasMoreElements()) {
            keyAlias = (String) aliases.nextElement();
            System.out.println("p12's alias----->" + keyAlias);
        }
        PrivateKey privateKey = (PrivateKey) ks.getKey(keyAlias, password.toCharArray());
        String privateKeyStr = Base64.encodeBase64String(privateKey.getEncoded());
        System.out.println("私钥------------->" + privateKeyStr);

        //公钥
        Certificate certificate = ks.getCertificate(keyAlias);
        String publicKeyStr = Base64.encodeBase64String(certificate.getPublicKey().getEncoded());
        System.out.println("公钥------------->" + publicKeyStr);
    }
}